/*
 * wwwAdapter: 
 * echo "" | ../gawk -F, 'BEGIN{extension("./libwwwAdapter.so","dlload"); loadConfig("config.xml");} { wwwAdapter(1,2,3) }' | head
 */


#ifdef DEFINE_SO

#include "Mcrypt.h"
extern "C" {
#include "awk.h"
}
#include <dlfcn.h>
#include <string>
using namespace std;

int plugin_is_GPL_compatible;
static void *sdl = NULL;


static NODE *
mcrypt_module_open(int nargs) {
    
    NODE *algorithm = get_scalar_argument(0, FALSE);
    NODE *mode = get_scalar_argument(1, FALSE);
    NODE *key = get_scalar_argument(2, FALSE);
    force_string(algorithm);
    force_string(mode);
    force_string(key);

    return make_number(wtt_mcrypt_module_open(algorithm->stptr, mode->stptr, key->stptr));
}

static NODE *
mcrypt_module_close(int nargs) {
    wtt_mcrypt_module_close();
}

static NODE *
mcrypt_generic(int nargs) {

    NODE *text = get_scalar_argument(0, FALSE);
    force_string(text);

    char *ret = wtt_mcrypt_generic(text->stptr);
    int len = strlen(ret);
    return make_string(ret, len);
}

static NODE *
mdecrypt_generic(int nargs) {

    NODE *text = get_scalar_argument(0, FALSE);
    force_string(text);

    char *ret = wtt_mdecrypt_generic(text->stptr);
    int len = strlen(ret);
    return make_string(ret, len);
}

extern "C" NODE *
dlload(NODE *tree, void *dl) {
    sdl = dl;
    make_builtin("mcrypt_module_open", mcrypt_module_open, 3);
    make_builtin("mcrypt_module_close", mcrypt_module_close, 0);

    make_builtin("mcrypt_generic", mcrypt_generic, 1);
    make_builtin("mdecrypt_generic", mdecrypt_generic, 1);

    return make_number((AWKNUM) 0);
}

#endif //DEFINE_SO
